package com.zx.ticket.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.zx.ticket.entity.Movie;
import com.zx.ticket.service.MovieService;
import com.zx.ticket.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/admin/movie")
public class movieController {

    @Autowired
    private MovieService movieService;


    @GetMapping("/")
    public String movie()
    {
        return "admin/movie";
    }



    @PostMapping("/addMovie")
    public @ResponseBody
    Movie addMovie(Movie movie, HttpServletRequest request, HttpSession session) {

        //保存数据库的路径
        String sqlPath = null;

        //获取跟目录
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("file:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (!path.exists()) {
            path = new File("");
            System.out.println("path:" + path);
        }

        //定义文件路径
        File upload = new File(path.getAbsolutePath(), "src/main/resources/static/image/upload/");
        if (!upload.exists()) {
            upload.mkdirs();
        }
        System.out.println("upload url:" + upload.getAbsolutePath());

        //定义 文件名
        String filename = null;
        if (!movie.getFile().isEmpty()) {
            //生成uuid作为文件名称
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //获得文件类型（可以判断如果不是图片，禁止上传）
            String contentType;
            contentType = movie.getFile().getContentType();
            //获得文件后缀名
            String suffixName = contentType.substring(contentType.indexOf("/") + 1);
            //得到 文件名
            filename = uuid + "." + suffixName;
            //调用文件上传工具类
            FileUtils.upload(movie.getFile(), upload.getAbsolutePath(), filename);
        }

        //把图片的相对路径保存至数据库
        sqlPath = "/image/" + filename;
        System.out.println(sqlPath);


        String name = request.getParameter("name");
        String ename = request.getParameter("ename");
        String type = request.getParameter("type");
        String country = request.getParameter("country");
        String duration = request.getParameter("duration");
        String showtime = request.getParameter("showtime");
        String score = request.getParameter("score");
        String votes = request.getParameter("votes");
        String introduce = request.getParameter("introduce");
        int directorId = Integer.parseInt(request.getParameter("director_id"));
        int performerId = Integer.parseInt(request.getParameter("performer_id"));

        movie.setImg(sqlPath);
        movie.setName(name);
        movie.setEname(ename);
        movie.setType(type);
        movie.setCountry(country);
        movie.setDuration(duration);
        movie.setShowtime(showtime);
        movie.setScore(score);
        movie.setVotes(votes);
        movie.setIntroduce(introduce);
        movie.setDirectorId(directorId);
        movie.setPerformerId(performerId);

        this.movieService.addMovie(movie);

        if (movie != null) {
            session.setAttribute("movie", movie);
            return movie;
        } else {
            return null;
        }
    }



    @DeleteMapping("/delete")
    public @ResponseBody
    String deleteMovie(int id) {
        System.out.println("-- -- -- -- -- -- --删除操作开始-- -- -- - -- -- -- --");

        int result = movieService.deleteMovie(id);
        System.out.println("打印结果：---------" + result + "----------");
        if (result == 1) {
            System.out.println("删除成功");
            return "success";
        } else {
            System.out.println("删除失败");
            return "error";
        }
    }

    @GetMapping("/index")
    public String findAll(Movie movie, Model model) {
        List<Movie> movieList =movieService.findAll(movie);
        model.addAttribute("movieList",movieList);
        return "admin/movie";
    }


    @PostMapping(value = "/update")
    public @ResponseBody String update(Movie movie, HttpServletRequest request, HttpSession session)
    {
        //保存数据库的路径
        String sqlPath = null;

        //获取跟目录
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("file:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (!path.exists()) {
            path = new File("");
            System.out.println("path:" + path);
        }

        //定义文件路径
        File upload = new File(path.getAbsolutePath(), "src/main/resources/static/image/upload/");
        if (!upload.exists()) {
            upload.mkdirs();
        }
        System.out.println("upload url:" + upload.getAbsolutePath());

        //定义 文件名
        String filename = null;
        if (!movie.getFile().isEmpty()) {
            //生成uuid作为文件名称
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //获得文件类型（可以判断如果不是图片，禁止上传）
            String contentType = movie.getFile().getContentType();
            //获得文件后缀名
            String suffixName = contentType.substring(contentType.indexOf("/") + 1);
            //得到 文件名
            filename = uuid + "." + suffixName;
            //调用文件上传工具类
            FileUtils.upload(movie.getFile(), upload.getAbsolutePath(), filename);
        }

        //把图片的相对路径保存至数据库
        sqlPath = "/image/" + filename;
        System.out.println(sqlPath);


        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String ename = request.getParameter("ename");
        String type = request.getParameter("type");
        String country = request.getParameter("country");
        String duration = request.getParameter("duration");
        String showtime = request.getParameter("showtime");
        String score = request.getParameter("score");
        String votes = request.getParameter("votes");
        String introduce = request.getParameter("introduce");
        int directorId = Integer.parseInt(request.getParameter("directorId"));
        int performerId = Integer.parseInt(request.getParameter("performerId"));

        movie.setId(id);
        movie.setImg(sqlPath);
        movie.setName(name);
        movie.setEname(ename);
        movie.setType(type);
        movie.setCountry(country);
        movie.setDuration(duration);
        movie.setShowtime(showtime);
        movie.setScore(score);
        movie.setVotes(votes);
        movie.setIntroduce(introduce);
        movie.setDirectorId(directorId);
        movie.setPerformerId(performerId);

        this.movieService.updateByPrimaryKey(movie);

        if (movie != null) {
            session.setAttribute("movie", movie);
            return "修改成功";
        } else {
            return null;
        }
    }


    @GetMapping("/movie/{id}")
    public @ResponseBody
    String findById(@PathVariable("id") Integer id)
    {
        List<Movie> movie = movieService.findById(id);
        JSONObject json = new JSONObject(true);
        json.put("status","200");
        json.put("msg","ok");
        json.put("method","GET");
        json.put("data",movie);
        return json.toJSONString();
    }
}
